<script setup lang="ts">
  import { ref, useTemplateRef } from 'vue'
  import { useQuasar } from 'quasar'

  import CudTable, { type TQTableColumns, type TRequestParam } from '@/components/CudTable.vue'
  import {
    batchRemindRent,
    batchUrgeRent,
    editRent,
    getOverdueBillPageList,
    getRentPageList,
    type TRentQueryParams
  } from '@/api'
  // import { isRequestSuccess } from '@/utils'

  const $q = useQuasar()
  const tab = ref('repair-man')
  const rDate = ref('')
  const rCompany = ref('')
  const rIsPaid = ref('')

  const manTableRef = useTemplateRef('repair-man')
  // const orderTableRef = useTemplateRef('repair-order')

  const manColumns: TQTableColumns = [
    { name: 'tenantId', label: '租客ID', field: 'tenantId', align: 'left' },
    { name: 'name', label: '姓名', field: 'name', align: 'left' },
    { name: 'company ', label: '公司', field: 'company ', align: 'left' },
    { name: 'phoneNumber', label: '电话', field: 'phoneNumber', align: 'left' },
    { name: 'monthlyRent', label: '月租金（单位：元/月）', field: 'monthlyRent', align: 'left' },
    {
      name: 'startDate',
      label: '日期区间',
      field: 'startDate',
      align: 'left',
      format: (val, _row) => `${val}~${_row.endDate}`
    },
    { name: 'isPaid', label: '是否缴纳', field: 'isPaid', align: 'left' }
  ]

  const orderColumns: TQTableColumns = [
    { name: 'tenantId', label: '租客ID', field: 'tenantId', align: 'left' },
    { name: 'name', label: '租客姓名', field: 'name', align: 'left' },
    { name: 'phoneNumber', label: '租客电话', field: 'phoneNumber', align: 'left' },
    { name: 'totalOverdueAmount', label: '租金', field: 'totalOverdueAmount', align: 'left' },
    {
      name: 'overdueMonths',
      label: '逾期月份',
      field: 'overdueMonths',
      align: 'left',
      format: val => val.join()
    }
  ]

  function manRequest(context: TRequestParam) {
    const { page, rowsPerPage } = context.pagination
    const params: TRentQueryParams = { pageNum: page, pageSize: rowsPerPage }
    if (rDate.value !== '') {
      params['startDate'] = rDate.value
      params['endDate'] = rDate.value
    }
    if (rCompany.value !== '') {
      params['company'] = rCompany.value
    }
    if (rIsPaid.value === '已缴纳') {
      params['isPaid'] = 1
    } else if (rIsPaid.value === '未缴纳') {
      params['isPaid'] = 0
    }
    return getRentPageList(params)
  }
  function orderRequest(context: TRequestParam) {
    const { page, rowsPerPage } = context.pagination
    const params: IPager = { pageNum: page, pageSize: rowsPerPage }
    return getOverdueBillPageList(params)
  }

  function onManSearch() {
    if (manTableRef.value) {
      manTableRef.value.refreshUserTable(1)
    }
  }
  function onKeyInput(event: KeyboardEvent) {
    if (event.key.toLowerCase() === 'enter') {
      // 13 为回车键
      onManSearch()
    }
  }
  async function onChangePaid(v: string, row: any) {
    const ov = row.isPaid
    const res = await editRent({ ...row, isPaid: v })
    if (res.data && res.data.code === 200) {
      $q.notify({
        type: 'positive',
        message: res.data.message || '修改成功'
      })
    } else {
      $q.notify({
        color: 'red-5',
        textColor: 'white',
        icon: 'warning',
        message: res.data.message || '修改失败'
      })
      row.isPaid = ov
    }
  }
  async function onBatchRemind() {
    const res = await batchRemindRent()
    if (res.data && res.data.code === 200) {
      $q.notify({
        type: 'positive',
        message: res.data.message || '交租提醒'
      })
    } else {
      $q.notify({
        color: 'red-5',
        textColor: 'white',
        icon: 'warning',
        message: res.data.message || '提醒失败'
      })
    }
  }
  async function onBatchUrge() {
    const res = await batchUrgeRent()
    if (res.data && res.data.code === 200) {
      $q.notify({
        type: 'positive',
        message: res.data.message || '已批量催缴'
      })
    } else {
      $q.notify({
        color: 'red-5',
        textColor: 'white',
        icon: 'warning',
        message: res.data.message || '催缴失败'
      })
    }
  }
</script>

<template>
  <q-page class="bg-[#FAFCFF] p-5">
    <q-tabs
      v-model="tab"
      dense
      active-color="primary"
      indicator-color="primary"
      align="left"
      narrow-indicator>
      <q-tab name="repair-man" label="租金月度统计" />
      <q-tab name="repair-order" label="逾期缴纳" />
    </q-tabs>

    <q-separator />

    <q-tab-panels v-model="tab" animated>
      <q-tab-panel name="repair-man">
        <CudTable
          ref="repair-man"
          class="bg-white"
          title="租金月度统计"
          row-key="tenantId"
          :columns="manColumns"
          :request="manRequest">
          <template v-slot:body-cell-isPaid="props">
            <q-td :props="props">
              <q-radio
                dense
                v-model="props.row.isPaid"
                @update:model-value="v => onChangePaid(v, props.row)"
                :val="1"
                label="已缴纳" />
              <q-radio
                dense
                class="q-ml-lg"
                @update:model-value="v => onChangePaid(v, props.row)"
                v-model="props.row.isPaid"
                :val="0"
                label="未缴纳" />
            </q-td>
          </template>
          <template v-slot:top-right>
            <!--            <div class="max-w-[300px] mr-3">
              <q-input
                outlined
                hide-bottom-space
                dense
                v-model="rDate"
                mask="date"
                :rules="['date']">
                <template v-slot:append>
                  <q-icon name="event" class="cursor-pointer">
                    <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                      <q-date v-model="rDate" emit-immediately flat>
                        <div class="row items-center justify-end">
                          <q-btn v-close-popup label="Close" color="primary" flat />
                        </div>
                      </q-date>
                    </q-popup-proxy>
                  </q-icon>
                </template>
              </q-input>
            </div>-->
            <q-input
              class="mr-3"
              outlined
              dense
              debounce="500"
              v-model="rCompany"
              @blur="onManSearch"
              @keydown="onKeyInput"
              placeholder="请输入公司查询">
              <template v-slot:append>
                <q-icon class="cursor-pointer" name="search" @click="onManSearch" />
              </template>
            </q-input>
            <q-select
              class="w-[200px] mr-3"
              v-model="rIsPaid"
              @update:model-value="onManSearch"
              :options="['已缴纳', '未缴纳']"
              label="是否已缴纳"
              outlined
              dense
              clearable
              options-dense></q-select>
            <q-btn color="primary" class="mr-3" label="下发交租提醒" @click="onBatchRemind" />
          </template>
        </CudTable>
      </q-tab-panel>

      <q-tab-panel name="repair-order">
        <CudTable
          ref="repair-order"
          class="bg-white"
          title="逾期缴纳"
          row-key="maintenanceOrderId"
          :columns="orderColumns"
          :request="orderRequest">
          <template v-slot:top-right>
            <q-btn color="primary" label="批量催缴" @click="onBatchUrge" />
          </template>
        </CudTable>
      </q-tab-panel>
    </q-tab-panels>
  </q-page>
</template>

<style scoped></style>
